#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>

// 将纳秒时间戳转换为带纳秒的字符串时间
std::string nanoTimestampToString(long long nanoTimestamp) {
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::nanoseconds(nanoTimestamp));
    auto nanoseconds = nanoTimestamp % 1000000000; // 获取纳秒部分

    time_t time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::time_point(seconds));
    struct tm *tm = std::localtime(&time);

    if (tm) {
        char buffer[80];
        strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm);
        std::ostringstream oss;
        oss << buffer << " " << std::setfill('0') << std::setw(9) << nanoseconds; // Append nanoseconds with leading zeros
        return oss.str();
    }

    return "Invalid Time"; // Handle error case
}

// 将字符串时间转换为纳秒时间戳
long long stringToNanoTimestamp(const std::string& timeString) {
    struct tm tm = {};
    std::istringstream iss(timeString);
    iss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");

    if (!iss.fail()) {
        auto timePoint = std::chrono::system_clock::from_time_t(std::mktime(&tm));
        int nanoseconds = 0;
        iss >> nanoseconds; // Read nanoseconds part

        return std::chrono::duration_cast<std::chrono::nanoseconds>(timePoint.time_since_epoch()).count() + nanoseconds;
    }

    return -1; // Handle error case
}

int main() {
    long long nanoTimestamp = 1636003800123456789; // Example nano timestamp
    std::string timeString = nanoTimestampToString(nanoTimestamp);
    std::cout << "String Time: " << timeString << std::endl;

    long long convertedNanoTimestamp = stringToNanoTimestamp(timeString);
    if (convertedNanoTimestamp != -1) {
        std::cout << "Converted Nano Timestamp: " << convertedNanoTimestamp << std::endl;
    } else {
        std::cout << "Invalid Time String" << std::endl;
    }

    return 0;
}
